﻿using Api.Shared.Model.Impl;
using Api.Shared.Responsitory.Sqlite;
using Api.Shared.Sugar;
using Api.Shared.Utils;
using Api.Shared.Utils.MyClient;
using FitterTest.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;

namespace FitterTest.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]
    [EnableCors("any")]
    public class TestController : ControllerBase
    {
        private readonly ISugarClientService service;
        private readonly SqliteRespository<Person> repPerson;
        private readonly IHttpClientFactory clientFactory;
        private readonly ILogger logger;

        public TestController(
            [FromKeyedServices(nameof(SqlName.sqlite))] ISugarClientService service,
            SqliteRespository<Person> repPerson,
            IHttpClientFactory clientFactory,
            ILogger<TestController> logger
        )
        {
            this.service = service;
            this.repPerson = repPerson;
            this.clientFactory = clientFactory;
            this.logger = logger;
        }

        [HttpGet]
        [CtmActionFilter2]
        public ActionResult<ApiResponse<Person>> GetPerson(int id, string name)
        {
            var person = new Person
            {
                Age = "15",
                Name = name,
                Id = id
            };

            ApiResponse<Person>? resp =
                new()
                {
                    Message = "成功",
                    Result = person,
                    Status = true,
                    Code = 200
                };

            return resp;
        }

        [HttpGet]
        [TypeFilter(typeof(CtmActionFilter3Attribute))]
        public ActionResult<Person> GetPerson2(int id, string name)
        {
            var person = new Person
            {
                Age = "15",
                Name = name,
                Id = id
            };

            return person;
        }

        [HttpGet("{a}")]
        public IActionResult Test2(string a)
        {
            if (a == "1")
            {
                throw new NotImplementedException();
            }

            return Ok();
        }

        //public IResult Hello() =>throw new NotImplementedException();

        [HttpGet]
        public IActionResult InitialTable()
        {
            service.Db.CodeFirst.SetStringDefaultLength(300).InitTables(typeof(Person));

            return Ok();
        }

        [HttpGet]
        public async Task<IActionResult> AddPerson()
        {
            List<Person> persons = new();
            for (int i = 0; i < 5; i++)
            {
                Person person = new() { Age = $"{i + 1}", Name = $"Tom{i + 1}" };
                persons.Add(person);
            }

            var a = await repPerson.InsertRangeAsync(persons);
            //repPerson.Context.Queryable<Person>().ToList();//.Context可以拿到db对象
            return Ok(a);
        }

        [HttpPost]
        public ActionResult<ApiResponse<Person2>> MyClientTest([FromBody] Person2 person)
        {
            ApiResponse<Person2>? resp =
                new()
                {
                    Message = "Success!",
                    Result = person,
                    Status = true,
                    Code = 200
                };
            return resp;
        }

        [HttpGet]
        public ActionResult<ApiResponse<Person>> MyClientTestGet()
        {
            var person = new Person { Age = "22", Name = "This is Get Res" };

            ApiResponse<Person>? resp =
                new()
                {
                    Message = "Success!",
                    Result = person,
                    Status = true,
                    Code = 200
                };
            return resp;
        }

        [HttpGet]
        public async Task<IActionResult> Mytt()
        {
            using HttpClient? client = clientFactory.CreateClient();
            client.Timeout = TimeSpan.FromSeconds(20);
            //client.BaseAddress = new Uri(ip);

            var baseRequest = new BaseRequest
            {
                Method = HttpMethod.Get,
                Route = "/api/Test/MyClientTestGet",
            };
            MyHttpClient myHttpClient = new(client, "myIp");
            var response = await myHttpClient.ExecuteAsync<Person>(baseRequest);
            JsonSerializerOptions options =
                new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, };
            var a = JsonSerializer.Serialize(response, options);
            logger.LogError(a);
            return Ok(a);
        }


    }
}
